<template>
  <div class="permission">
    <el-card>
      <!-- 头部按钮 -->
      <div class="btnbox">
        <el-button type="primary" size="mini" @click="openadd(1,'0')">
          <i class="el-icon-edit" />添加菜单
        </el-button>
      </div>
      <!-- 表格 -->
      <el-table :data="perlist" row-key="id">
        <el-table-column label="菜单名称" prop="name" />
        <el-table-column label="权限标识" prop="code" />
        <el-table-column label="描述" prop="description" />
        <el-table-column label="操作">
          <template slot-scope="{row}">
            <el-button v-if="row.type===1" type="text" @click="openadd(2,row.id)">添加权限点</el-button>
            <el-button type="text">查看api权限</el-button>
            <el-button type="text" @click="openedit(row.id)">编辑</el-button>
            <el-button type="text" @click="delper(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <panel ref="editpanel" :showdialog.sync="showdialog" @updateye="getAllPer" />
    <add ref="addpanel" :showadddia.sync="showadddia" @updateye="getAllPer" />
  </div>
</template>

<script>
import { getAllPerApi, deletePerApi } from '@/api/permission'

export default {
  components: {
    panel: () => import('@/views/permission/component/panel.vue'),
    add: () => import('@/views/permission/component/add.vue')
  },
  data() {
    return {
      // 权限列表
      perlist: [],
      // 编辑弹框显示
      showdialog: false,
      // 添加弹框显示
      showadddia: false,
      // 添加属性
      type: '',
      pid: ''
    }
  },
  created() {
    this.getAllPer()
  },
  methods: {
    // 点击添加打开新增权限面板
    openadd(type, pid) {
      this.showadddia = true

      this.$refs.addpanel.setprop(type, pid)
    },
    // 点击编辑打开编辑权限面板
    openedit(id) {
      this.showdialog = true
      this.$refs.editpanel.getPer(id)
    },
    // 获取所有权限列表
    async getAllPer() {
      const res = await getAllPerApi()
      console.log(res)
      this.perlist = this.trunData(res, '0')
      console.log(this.perlist)
    },
    // 转成树状结构
    trunData(arr, pid) {
      const newArr = []
      arr.forEach(item => {
        if (item.pid === pid) {
          item.children = this.trunData(arr, item.id)
          newArr.push(item)
        }
      })
      return newArr
    },
    // 删除权限点
    async delper(id) {
      try {
        await this.$confirm('确定删除权限吗', '警告')
        // 调用删除权限接口
        await deletePerApi(id)
        this.$message.success('删除权限成功')
        // 刷新页面
        this.getAllPer()
      } catch {
        console.log('出错了')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.permission {
  padding: 20px;
  .btnbox {
    text-align: right;
  }
}
</style>
